/**
 * 账号管理
 * @constructor
 */
function AccountMange() {
}

AccountMange.init = function () {

    getBreedSonMenu();

    $('#tableList').bootstrapTable({
        url: '/users/tableSearch',
        method: 'post',
        striped : true, //是否显示行间隔色
        toolbar: "#toolbar",
        sidePagination: "true",
        dataField: "data",//这是返回的json数组的key.默认是"rows".这里只有前后端约定好就行
        showToggle : true, //是否显示详细视图和列表视图的切换按钮
        striped: true, // 是否显示行间隔色
//search : "true",
        uniqueId: "id",
        pageList : [ 5, 10, 20,50,100],//可选择单页记录数
        pageSize: "10",
        pagination: true, // 是否分页
        sortable: true, // 是否启用排序
        sidePagination: 'server', // 设置为服务器端分页     客户端：client
        search:false,
        showColumns: true,
        showRefresh: true,
        showExport: true,
//得到查询的参数
        queryParams: function (params) {
//这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var query_params = {
//********table的参数 不变
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
//********
//获取查询的对象，往下加入
                userName: $('#search_userName').val(), // 请求时向服务端传递的参数
                realName: $('#search_realName').val(),
                phone:  $('#search_phone').val(),
            };
            return query_params;
        },
        columns: [
            {
//field: 'Number',//可不加
                title: '序号',//标题  可不加
                align: "center",
                width: 40,
                formatter: function (value, row, index) {
                    var pageSize=$('#tableList').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                    var pageNumber=$('#tableList').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                }
            },
            { field: 'userName', title: '登录名',align: 'center'},
            { field: 'realName', title: '真实姓名',align: 'center'},
            { field: 'phone', title: '联系电话',align: 'center'},
            { field: 'userMenuNames', title: '权限',align: 'center'},
            { field: 'activity',
                title: '状态',
                align: 'center',
                formatter: function (value, row, index) {
                    if(value ==1){
                        return '<span class="label label-success">启用</span>';
                    }
                    return '<span class="label label-danger">停用</span>';

            }},
            { field: 'createDateTime', title: '创建日期',align: 'center'},
            {
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";
                    optionHtml = optionHtml+"<a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"edit\")' title=\"修改\" ><i class=\"fa fa-edit\"></i>修改</a>";
                    optionHtml = optionHtml + " <a class=\"btn btn-warning btn-xs\" href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"resetPwd\")'  title=\"重置密码\"><i class=\"fa fa-retweet\"></i>重置密码</a>"
                    if(row.activity == 0){
                        optionHtml = optionHtml + " <a class=\"btn btn-success btn-xs\" href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"enable\")'  title=\"启用\"><i class=\"fa fa-check-circle-o\"></i>启用</a>"
                    }else{
                        optionHtml = optionHtml + " <a class=\"btn btn-danger btn-xs\" href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"disable\")'  title=\"停用\"><i class=\"fa fa-ban\"></i>停用</a>"
                    }
                    optionHtml = optionHtml + " <a class=\"btn btn-danger btn-xs\" href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"delete\")'  title=\"删除\"><i class=\"fa fa-remove\"></i>删除</a>"
                    return optionHtml;
                }
            }
        ]
    });
}


//查询方法****************************
function doSearch() {
// $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
    $("#tableList").bootstrapTable("refreshOptions",{pageNumber:1});
}
//重置****************************
function doRest() {
   $('#search_userName').val("");
   $('#search_realName').val("");
   $('#search_phone').val("");
    // $("#search_Enterprise").val("");
// $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
    $("#tableList").bootstrapTable("refreshOptions",{pageNumber:1});
}
//增加方法****************************
var Action="";
var userID=0;
var pxt="/users"; //控制器名称
function addRecord() {
    userID=0;
    Action="add";
    $('#text_userName').removeAttr('readonly');
    $('#text_realName').removeAttr('readonly');
    $("#myform")[0].reset();
    $("input[name='menu']").removeAttr('checked').iCheck('update');
    $("input[name='text_activity']").removeAttr('checked').iCheck('update');
    $("input[name='text_activity'][value='1']").iCheck('check');
    $('#nameContainer').show();
    $('#passwordContainer').show();
    $('#phoneContainer').show();
    $('#preContainer').show();
    $('#statusContainer').show();

}
//增加/修改数据保存****************************
function saveRecord() {
    if(!validateForm()) return false;
//创建传递的参数
    var postdata = {
        userID: userID,
        action:Action,
        userName: $("#text_userName").val(),
        realName: $("#text_realName").val(),
        password: $("#text_password").val(),
        phone: $("#text_phone").val(),
        activity: getValue("text_activity"),
        userMenuIds:getValue("menu"),
        userMenuNames:getName("menu"),
        userType: userType
    };
    var func = "/save";
    if(Action == "edit"){
        func = "/update";
    }else if (Action == "resetPwd"){
        func = "/resetPwd"
    }
//发送异步请求到后台保存用户数据
    $.ajax({
        url:pxt+func,
        type:"post",
        data:JSON.stringify(postdata),
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                doSearch();
                swal("操作成功!", "请继续操作", "success");
            } else {
                swal("操作失败!", data.message, "error");
            }
        }
    });
}

//操作相关方法****************************
function actionRecord(data,type) {
    $('#nameContainer').show();
    $('#passwordContainer').show();
    $('#phoneContainer').show();
    $('#preContainer').show();
    $('#statusContainer').show();
    if(type=="edit")
    {
//修改
        $('#text_userName').attr('readonly','readonly');
        $('#passwordContainer').hide();
        userID=data.userID;
        Action="edit";
        $("#myform")[0].reset();
        $("#save").removeAttr("disabled");
        WriteData(data)
        $('#myModalAdd').modal('show')
    }
    else if(type=="enable")
    {
        swal({
            title: "确认是否启用",
            text: "是否确认要启用该账号？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "启用",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
//点击删除之后此处进行传递后台
            $.ajax({
                type: "post",
                url: pxt+"/enable/"+data.userID,
                dataType : "json",
                contentType: "application/json",
                success: function (data, status) {
                    if (data.code == "200") {
                        doSearch();
                        swal("操作成功!", "请继续操作", "success");
                    }
                    else{
                        swal("操作失败!", "请重试", "error");
                    }
                }
            });
        });
    }
    else if(type=="disable")
    {
        swal({
            title: "确认是否停用",
            text: "是否确认要停用该账号？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "停用",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
//点击删除之后此处进行传递后台
            $.ajax({
                type: "post",
                url: pxt+"/disable/"+data.userID,
                dataType : "json",
                contentType: "application/json",
                success: function (data, status) {
                    if (data.code == "200") {
                        doSearch();
                        swal("操作成功!", "请继续操作", "success");
                    }
                    else{
                        swal("操作失败!", "请重试", "error");
                    }
                }
            });
        });
    }
    else if(type=="resetPwd")
    {
        userID=data.userID;
        Action="resetPwd";
        $("#myform")[0].reset();
        $("#save").removeAttr("disabled");
        $('#text_userName').attr('readonly','readonly');
        $('#text_realName').attr('readonly','readonly');
        $('#phoneContainer').hide();
        $('#preContainer').hide();
        $('#statusContainer').hide();
        $("#myform")[0].reset();
        $("#save").removeAttr("disabled");
        WriteData(data)
        $('#myModalAdd').modal('show')
    }
    else
    {
//删除
        swal({
            title: "确认是否删除",
            text: "是否确认要删除该条记录？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
//点击删除之后此处进行传递后台
            $.ajax({
                type: "delete",
                url: pxt+"/deleteById/"+data.userID,
                dataType : "json",
                contentType: "application/json",
                success: function (data, status) {
                    if (data.code == "200") {
                        doSearch();
                        swal("删除成功!", "请继续操作", "success");
                    }
                    else{
                        swal("删除失败!", "请重试", "error");
                    }
                }
            });

        });
    }
}

//给控件赋值****************************
function WriteData(data) {
    $("#text_userName").val(data.userName);
    $("#text_realName").val(data.realName);
    $("#text_phone").val(data.phone);
    $("input[name='text_activity']").each(function () {
        if($(this).val() == data.activity){
            $(this).iCheck('check');
        }else{
            $(this).removeAttr('checked').iCheck('update');
        }
    })
    $("input[name='menu']").each(function () {
        if(data.userMenuIds && data.userMenuIds.split(',').indexOf($(this).val())>-1){
            $(this).iCheck('check');
        }else{
            $(this).removeAttr('checked').iCheck('update');
        }
    })
}

jQuery.validator.addMethod("passwordValidator", function(value, element) {
    var pwd = $('#text_password').val();
    var pwdConfirm = $('#text_passwordConfirm').val();
    if(pwd!='' && pwdConfirm!='' && pwdConfirm!=pwd){
        return false;
    }
    return true;
}, "(登录密码与确认密码不一致)");


jQuery.validator.addMethod("isPhone", function(value, element) {
    var phone = $('#text_phone').val();
    if(phone!=''){
        var reg01 = /^(0|86|17951)?(13[0-9]|15[012356789]|17[01678]|18[0-9]|14[57])[0-9]{8}$/;
        var reg02 = /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
        if(!reg01.test(phone) && !reg02.test(phone)){
            return false
        }
    }
    return true;
}, "(请输入正确的联系方式)");

//表单验证*****************************
function validateForm() {
//validate方法参数可选
    return $("#myform").validate({
        rules: {
            text_userName: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
            },
            text_realName: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
            },
            text_phone: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                isPhone: true,
                // number: true, //必须是数字
            },
            text_password: {
                required: true,//必填
                minlength: 6, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_passwordConfirm: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                passwordValidator: true
                // number: true, //必须是数字
            }
        },
//错误信息提示
        messages: {
            text_userName: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_realName: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
            },
            text_phone: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                isPhone: "(请输入正确的联系方式)"
                // number: true, //必须是数字
            },
            text_password: {
                required: "(必填)",
                minlength: "(至少六个字符)", //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_passwordConfirm: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                passwordValidator : "(登录密码与确认密码不一致)"
                // number: true, //必须是数字
            }
        },
    }).form();

}

function getValue(name) {
    var str = '';
    $("input[name='"+name+"']").each(function () {
        if($(this).prop('checked')){
            str += $(this).val() +',';
        }
    })
    return str==''?str:str.substr(0,str.length-1);
}

function getName(name) {
    var str = '';
    $("input[name='"+name+"']").each(function () {
        if($(this).prop('checked')){
            str += $(this).parent().parent().text().trim() +',';
        }

    })
    return str==''?str:str.substr(0,str.length-1);
}

//获得子菜单
function getBreedSonMenu() {
    //清空
    $("#BreedSonMenu").empty();
    $.ajax({
        type: "post",
        url: pxt+"/getBreedSonMenu",
        dataType : "json",
        contentType: "application/json",
        success: function (data, status) {
            if (data.code == "200") {
                $.each(data.data.Menus,function (index,obj) {
                    $("#BreedSonMenu").append("<div class=\"col-lg-3\">\n" +
                        "                          <label class=\"checkbox-inline\">\n" +
                        "                              <input type=\"checkbox\" name=\"menu\"  value=\""+obj.menuId+"\"> "+obj.textCH+"\n" +
                        "                          </label>\n" +
                        "                       </div>");
                })
            }
        }
    });
}
